﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Grpc.Core;
using System;

namespace Md.Demo.API
{
    public class GlobalException
    {
        public static void ExceptionHandler(IApplicationBuilder errApp)
        {
            errApp.Run(context =>
            {
                var feature = context.Features.Get<IExceptionHandlerFeature>();
                context.Response.StatusCode = 200;
                context.Response.ContentType = "application/json; charset=utf-8";
                switch (feature?.Error)
                {
                    case RpcException ex:
                        context.Response.WriteAsync(JsonConvert.SerializeObject(new { errmsg = ex.Status.Detail, errno = 500 }));
                        break;
                    case Exception ex:
                        context.Response.WriteAsync(JsonConvert.SerializeObject(new { errmsg = feature.Error.Message, errno = 500 }));
                        break;
                }
                return Task.CompletedTask;
            });
        }
    }
}
